<?php
class SyscolumnAction extends Action{
    public function _initialize(){//初始化验证
	    if(empty($_SESSION["admin"])) 
		$this->redirect("Login/index");
		//权限最大的管理员
		$admin=M("admin");
		$pression_arr=$admin->field("admin,pression")->findAll();
		foreach($pression_arr as $k=>$v){
		   $admin_arr[$v['admin']]=count(explode(",",$v['pression']));
		}
		asort($admin_arr);
		$max_pression_admin=end(array_keys($admin_arr));
		if(strcmp($max_pression_admin,$_SESSION["admin"]))alert('只有超级管理员才有此权限');
	}
    public function index(){//栏目管理
	   $parid=saferequest($_GET["parid"]);
	   if(empty($parid)) $parid=0;
	   $syscolumn=M("syscolumn");
	   $maxseq=$syscolumn->where("parid=$parid")->max("sequence");
	   $minseq=$syscolumn->where("parid=$parid")->min("sequence");
	   $syscolumns=$syscolumn->where("parid=$parid")->order("sequence desc")->findAll();
	   $this->assign("minseq",$minseq);
	   $this->assign("maxseq",$maxseq);
	   $this->assign("syscolumns",$syscolumns);
	   $this->display();
	}
	
	public function add(){//添加栏目
	   $parid=saferequest($_GET["parid"]);
	   $this->assign("parid",$parid);
	   $this->display();
	}
    
	public function insert(){//添加
	    $parid=saferequest($_GET["parid"]);
		if(!empty($_POST["col_eng_name"]))create_column($_POST["col_name"],$_POST["col_eng_name"]);
		$syscolumn=D("syscolumn");
		$maxseq=$syscolumn->where("parid = $parid")->max("sequence");
		$maxseq++;
		$_POST["sequence"]=$maxseq;
		$_POST["parid"]=$parid;
		//修改 lijianwei 2010.12.31  栏目栏目网址
	    if(!empty($_POST["col_url"]))$_POST["col_url"]=format_col_url($_POST["col_url"]);
		if($vo=$syscolumn->create()){
		    $syscolumn_id=$syscolumn->add();
			if($syscolumn_id!==false){
			   $this->success("栏目添加成功!");
			}else{
			   $this->error("数据写入错误!");
			}
		}else{
		   $this->error($syscolumn->getError());
		}
	}
	
	public function edit(){//修改
	   $id=saferequest($_GET["id"]);
	   $syscolumn=M("syscolumn");
	   $syscolumns=$syscolumn->where("id = $id")->find();
	   $this->assign("id",$id);
	   $this->assign("syscolumns",$syscolumns);
	   $this->display();
	}
     
	public function update(){
	   $syscolumn=D("syscolumn");
	   $table=$_GET["table"];
	   $id=$_POST["id"];
	   $parid=$syscolumn->where("id=$id")->getField("parid");
	   $old_eng_name=$syscolumn->where("id=$id")->getField("col_eng_name");
	   if(!empty($_POST["col_eng_name"])) update_column($_POST["col_name"],$old_eng_name,$_POST["col_eng_name"]);
	   
       if(empty($_POST["is_search"])) $_POST["is_search"]=0;
	   
	   //修改 lijianwei 2010.12.31  栏目栏目网址
	   if(!empty($_POST["col_url"]))$_POST["col_url"]=format_col_url($_POST["col_url"]);
	   if($syscolumn->create()){
	      $result=$syscolumn->save();
	      if($result!==false){
		     $this->success("栏目更新成功");
		  }else{
		     $this->error("栏目更新失败");
		  }
	   }else{
	      $this->error($syscolumn->getError());
	   }
	
	}
	 
	public function del(){//删除
	  $id=saferequest($_GET["id"]);
	  if(empty($id)) $this->error("删除项不存在");
	  $syscolumn=M("syscolumn");
	  
	  //调用delete_column($this->table);
	  $col_eng_name=$syscolumn->where("id=$id")->getField("col_eng_name");
	  $parid=$syscolumn->where("id=$id")->getField("parid");
      if(!empty($col_eng_name)) delete_column($col_eng_name);
	  $syscolumn->startTrans();//启动事务
	  $result=$syscolumn->delete($id);
	  $childres=$syscolumn->where("parid = $id")->delete();//删除子栏目
	  if($result!==false&&$childres!==false){
	     $syscolumn->commit();//事务提交
	     $this->success("删除成功");
	  }else{
	     $syscolumn->rollback();//事务回滚
	     $this->error("删除出错");
	  }
	}
	
	public function up(){//上调
	   $id=saferequest($_GET["id"]);
	   $syscolumn=M("syscolumn");
	   $c=$syscolumn->where("id=$id")->find();
	  
	   $seq=$c["sequence"];
	   $parid=$c["parid"];
	       
	   $map["parid"]=$parid;
	   $map["sequence"]=array("gt",$seq);
	   $n=$syscolumn->where($map)->order("sequence asc")->find();
	   
	   $nextseq=$n["sequence"];
	   $nextid=$n["id"];

       //修改
	   $syscolumn->sequence=$seq;
	   $syscolumn->save();
	   
	   $syscolumn->where("id=$id")->find();
	   $syscolumn->sequence=$nextseq;
	   $syscolumn->save();

	   
	   $e=$syscolumn->geterror();
	   if(!$e){
	       $this->redirect("index",array("parid"=>$parid));
	   }else{
	      $this->error("修改失败");
	   }
	}
	
	public function down(){//下调
	   $id=saferequest($_GET["id"]);
	   $syscolumn=M("syscolumn");
	   $c=$syscolumn->where("id=$id")->find();
	  
	   $seq=$c["sequence"];
	   $parid=$c["parid"];
	       
	   $map["parid"]=$parid;
	   $map["sequence"]=array("lt",$seq);
	   $n=$syscolumn->where($map)->order("sequence desc")->find();
	   
	   $nextseq=$n["sequence"];
	   $nextid=$n["id"];
       //修改
	   $syscolumn->sequence=$seq;
	   $syscolumn->save();
	   
	   $syscolumn->where("id=$id")->find();
	   $syscolumn->sequence=$nextseq;
	   $syscolumn->save();
	   
	   $e=$syscolumn->geterror();
	   if(!$e){
	      $this->redirect("index",array("parid"=>$parid));
	   }else{
	      $this->error("修改失败");
	   }
	}
	
	public function setshow(){
	   $parid=$_GET["parid"];
	   if(isset($_GET["is_show"])){
		     $is_show=$_GET["is_show"];
			 $is_show=($is_show)?0:1;
			 $id=$_GET["id"];
			 $syscolumn=M("syscolumn");
			 $syscolumn->where("id=$id")->setField("is_show",$is_show);
	   }elseif(isset($_GET["left_show"])){
		     $left_show=$_GET["left_show"];
			 $left_show=($left_show)?0:1;
			 $id=$_GET["id"];
			 $syscolumn=M("syscolumn");
			 $syscolumn->where("id=$id")->setField("left_show",$left_show);		   
	   }
	   $this->redirect("index",array("parid"=>$parid));
	}
  public function del_cache(){
  	Vendor("LJW.Inc_File");
  	$myfile=new Inc_File();
  	if($myfile->deletedir(APP_NAME."/RunTime",false)){//不删除runtime
	   //删除后台缓存
	   $dir=dir(APP_NAME."/Html");
	   while(false!==($file=$dir->read())){
	      if($file=="."||$file=="..")continue;
		  if(is_dir(APP_NAME."/Html/".$file))$myfile->deletedir(APP_NAME."/Html/".$file);
		  if(is_file(APP_NAME."/Html/".$file)) $myfile->deleteFile(APP_NAME."/Html/".$file);
	   }
  	   $this->success("操作成功");
  	}else{
  	   $this->error("操作失败");
  	}
  }
  public function execute_sql(){
     $this->display();
  }
  public function do_sql(){
	 $sql=$_POST["sql_text"];
	 $sql=trim($sql);
	 if(get_magic_quotes_gpc()) $sql=stripslashes($sql);
	 ob_start();
	 if($result=check_and_execute_sql($sql)){
		$sql_arr=explode("|||",$sql);
	    foreach($result as $k=>$v){
			echo "<span style='display:block;margin-top:20px;'>".$sql_arr[$k]."返回".count($v['data'])."条结果,耗时".$v['runtime']."</span>";
			$fields=array_keys($v['data'][0]);
			$newdata=array();
			foreach($v["data"] as $mm=>$nn){
				$newdata[]=array_values($nn);
			}
			echo "<table border='1' cellpadding='0' cellspacing='0' width='400'>";
			echo "<tr>";
			foreach($fields as $vv){
			  echo "<td>$vv</td>";	
			}
			echo "</tr>";
			foreach($newdata as $mm=>$nn){
				echo "<tr>";
				  foreach($nn as $val){
					  echo "<td>$val</td>";  
				  }
				echo "</tr>";
			}
			echo "</table>";
		}
		$content=ob_get_contents();
		ob_end_clean();
		$this->assign("content",$content);
		$this->assign("oldsql",$sql);
		$this->display("execute_sql");
	 }else{
	   alert('执行失败');
	 }
  }
  public function remove_notshow_img(){//去除二级目录图片不显示  
	   header("Content-type:text/html;charset=utf-8");
	   if(empty($_GET["action"])){
           $this->display();
		   exit;
	   }
	   checkpost("111");
	   $second_dir=$_POST['second_dir'];
	   $new_second_dir=$_POST['new_second_dir'];
	   if(empty($second_dir)) exit("second_dir 为空，不能执行");
	   if(empty($new_second_dir)) exit("替换目录 为空，不能执行");
	   //主要是编辑框中上传的图片当上传到域名时，因为目录图片不显示,例以前的图片路径是  /puti/Public/Uploads/  修改为 /Public/Uploads/  /puti/Public/images/  替换为/Public/images/

	   //原理：找到数据库中 字段类型为text的字段名称和对应表 组合sql语句
	   $conn=@mysql_connect(C("DB_HOST"),C("DB_USER"),C("DB_PWD")) or die("can't connect db");
	   @mysql_select_db(C("DB_NAME"),$conn) or die("can't select db");
       $sql="show tables";
	   $result=@mysql_query($sql);
	   $tables=array();
	   while($list=mysql_fetch_array($result)){
            array_push($tables,$list[0]);
	   }
	   mysql_free_result($result);
	   $text_fields=array();
	   //修改 lijianwei 新增 mediumtext longtext
	   $text_arr=array("text","mediumtext","longtext");
	   foreach($tables as $k=>$v){
		   $sql="show columns from $v";
		   $result=mysql_query($sql);
		   while($list=mysql_fetch_array($result)){
               $type=strtolower($list["Type"]);
			   if(in_array($type,$text_arr)){
				   $text_fields[$k]["fields"][]=$list["Field"];
			       $text_fields[$k]["table"]=$v;
			   }
		   }
	   }
	   //组成sql语句
	   $sql_array=array();
	   foreach($text_fields as $k=>$v){
		  $table=$v["table"];
		  $fields=$v["fields"];
		  $replace_sql=array();
		  foreach($fields as $m){
              $replace_sql[]="$m=replace($m,'$second_dir','$new_second_dir')";
		  }
          $sql_array[]="update $table set ".implode(",",$replace_sql); 
	   }
	   foreach($sql_array as $v){
	       @mysql_query($v,$conn);
	   }
	   @mysql_close($conn);
       alert("执行成功");
  }
  public function analysis_table(){//分析数据表
	  checkpost();
	  checkget();
	  if($_GET["action"]=="ajax_get_dbs"){//获取数据库列表
	      $server=$_GET["server"];
		  $username=$_GET["username"];
		  $password=$_GET["password"];
		  $link=mysql_connect($server,$username,$password);
		  $sql="show databases";
		  $result=mysql_query($sql,$link);
		  while($arr=mysql_fetch_array($result)){
			 $options.="<option value='$arr[0]'>$arr[0]</option>";
		  }
		  echo $options;
		  exit;
	  }else if($_GET["action"]=="ajax_get_tables"){//获取数据表
	      $server=$_GET["server"];
		  $username=$_GET["username"];
		  $password=$_GET["password"];
		  $db=$_GET["db"];
		  $link=mysql_connect($server,$username,$password);
		  mysql_select_db($db);
		  $sql="show tables from $db";
		  $result=mysql_query($sql,$link);
		  while($arr=mysql_fetch_array($result)){
			 $options.="<option value='$arr[0]'>$arr[0]</option>";
		  }
		  echo $options;
		  exit;
	  }else if($_GET['action']=="importsys"){
		  set_time_limit(0);
		  $server=$_POST["server"];
		  $username=$_POST["username"];
		  $password=$_POST["password"];
		  $db=$_POST["dbs"];
		  $table=$_POST["tables"];
		  //多数据库切换
		  $advmodel=new AdvModel;
		  //查询现有数据表
		  $sql="show tables";
		  $curr_tables_arr=$advmodel->query($sql);
		  foreach($curr_tables_arr as $k=>$v){
			   $curr_tables[]=current($v);
		  }
		  
		  $myconnect=array(
		    'dbms'     => 'mysql',  
			'username' => $username,  
			'password' => $password,  
			'hostname' => $server,  
			'hostport' => '3306',  
			'database' => $db,
		  );
		  $advmodel->addConnect($myconnect,1);
		  $advmodel->switchConnect(1,$table);
		  //考虑如果有前缀的表,去除前缀
		  if(strpos($table,"_")){
			  $create_table=array_pop(explode("_",$table));
		  }else{
              $create_table=$table;
		  }
		  //首先验证当前数据库是否已经存在$table,如果存在
		  if(false!==array_search($create_table,$curr_tables,true)){
			  $create_table=$create_table."_1";
		  }
		  $sql="show create table $table";
		  $create_table_sql_arr=$advmodel->query($sql);
		  $create_table_sql=$create_table_sql_arr[0]['Create Table'];
		  if(!empty($create_table)){
			  $pattern="/(CREATE TABLE )(`$table`)/";
			  $replace="\$1`$create_table`";
			  $create_table_sql=preg_replace($pattern,$replace,$create_table_sql);
		  }
		  $sql="show full columns from $table";
		  $table_field_info=$advmodel->query($sql);
		  $sysfield=M("sysfield");
		  foreach($table_field_info as $k=>$v){
			  if($v["Field"]==$advmodel->getPk())continue;
			  $i++;
			  $data=array();
			  $data["field_name"]=$v["Field"];
			  $type_str=$v["Type"];
			  preg_match("/([^\(\)]+)(\()*(\d*)(\))*/",$type_str,$matches);
			  $type=$matches[1];
			  $num=$matches[3];
			  $data["field_type"]=$type;
			  $data["field_length"]=$num;
			  $data["field_comment"]=$v["Comment"];
			  switch($type){
				 case "varchar":
				 case "char":
				   $data["field_output_type"]="单行文本框";
				   $data["field_output_length"]=50;
				   break;
				 case "tinyint":
				 case "smallint":
				 case "mediumint":
				 case "int":
				 case "bigint":
				   $data["field_output_type"]="下拉框";
				   $data["field_output_length"]=0;
				   break;
				 case "text":
				 case "mediumtext":
				 case "longtext":
				   $data["field_output_type"]="多行文本框";
				   $data["field_output_length"]=0;
			  }
			  $data["field_notice"]="";
			  $data["field_value_fill_type"]="默认填充(字段)";
			  $data["field_value_fill"]=0;
			  $data["field_default_value"]=0;
			  $data["field_isuse"]=1;
			  $data["field_isdetail"]=1;
			  $data["field_islist"]=1;
			  $data["col_eng_name"]=$create_table;
			  $data["sequence"]=count($table_info)-$i;
			  $sysfield->add($data);
		  }
		  //创建数据表
		  $sysfield->query($create_table_sql);
		  $col_eng_name=$create_table;
		  $newmodel=M($col_eng_name);
		  //如果原数据表中有数据，则拷贝数据
		  $oldlist=$advmodel->findAll();
		  if(!empty($oldlist)){
			  foreach($oldlist as $k=>$v){
				 $newmodel->add($v); 
			  }
		  }
		  //获取原表表名注释
		  $sql="show table status like '$table'";
		  $table_info=$advmodel->query($sql);
		  $comment=$table_info[0]['Comment'];
		  if(!empty($comment)) $comment=array_shift(explode(";",$comment));
		  //创建栏目  添加栏目 编辑栏目
		  create_sys_column($col_eng_name,$comment);
		  $this->redirect("analysis_table","",1,"分析成功");
	  }
	  $this->display();
  }
  public function allcolumn_edit(){
	set_time_limit(60);
	$syscolumn=M("syscolumn");
	$syscolumns=$syscolumn->where("col_eng_name <> ''")->order("sequence desc")->field("col_eng_name")->findAll();
	$eng_name_arr=array();
	foreach($syscolumns as $k=>$v){
	   	array_push($eng_name_arr,$v['col_eng_name']);
	}
	if(array_walk($eng_name_arr,"column_edit")){
		$this->success("全部重新生成栏目成功");
	}else{
	    $this->success("全部重新生成栏目失败");
	}
	
  }
  public function sysfield_group(){//字段分组
      checkpost();
	  checkget();
	  $table=$_GET["table"];
	  if(empty($table))alert('参数错误');
	  $this->assign("table",$table);
	  $action=$_GET["action"];
	  //获取先有字段分组情况
	  $sysfield_group=D("sysfield_group");
	  $map["col_eng_name"]=$table;
	  $sg_list=$sysfield_group->where($map)->order("sequence desc")->findAll();
	  $this->assign("sg_list",$sg_list);
	  $maxseq=$sysfield_group->where($map)->max("sequence");
	  $minseq=$sysfield_group->where($map)->min("sequence");
	  $this->assign("maxseq",$maxseq);
	  $this->assign("minseq",$minseq);
	  
	  $action=$_GET["action"];
	  switch($action){
		 case "up":
		    $id=$_GET["id"];
			$curr_seq=$sysfield_group->where("id=$id")->getField("sequence");
			
			$next_info=$sysfield_group->where("sequence > $curr_seq")->order("sequence asc")->field("id,sequence")->find();
			$next_id=$next_info['id'];
			$next_sequence=$next_info['sequence'];
			
			$sysfield_group->where("id=$id")->setField("sequence",$next_sequence);
			$sysfield_group->where("id=$next_id")->setField("sequence",$curr_seq);
			$this->redirect("sysfield_group",array("table"=>$table));
		 break;
		 case "down":
		    $id=$_GET["id"];
			$curr_seq=$sysfield_group->where("id=$id")->getField("sequence");
			
			$next_info=$sysfield_group->where("sequence < $curr_seq")->order("sequence desc")->field("id,sequence")->find();
			$next_id=$next_info['id'];
			$next_sequence=$next_info['sequence'];
			
			$sysfield_group->where("id=$id")->setField("sequence",$next_sequence);
			$sysfield_group->where("id=$next_id")->setField("sequence",$curr_seq);
			$this->redirect("sysfield_group",array("table"=>$table));
		 break;
		 case "edit":
		     $id=$_GET["id"];
		     $sg_info=$sysfield_group->where("id=$id")->find();
		     $this->assign("sg_info",$sg_info);
		 break;
		 case "update":
		     $data["id"]=$_POST["id"];
			 $data["group_name"]=$_POST["group_name"];
			 $sysfield_group->save($data);
			 $this->redirect("sysfield_group",array("table"=>$table));
		 break;
		 case "insert":
		     $data["group_name"]=$_POST["group_name"];
			 $data["col_eng_name"]=$table;
			 $data["sequence"]=++$maxseq;
			 $sysfield_group->add($data);
			 $this->redirect("sysfield_group",array("table"=>$table));
		 break;
		 case "delete":
		     $id=$_GET["id"];
			 $sysfield_group->where("id=$id")->delete();
			 //把sysfield中相关记录清零
			 $sysfield=M("sysfield");
			 $sysfield->where("col_eng_name='$table' and field_group_id=$id")->setField("field_group_id",0);
			 $this->redirect("sysfield_group",array("table"=>$table));
		 break;
	  }
	  $this->display();
  }
  
  public function sysregion(){
	  header("content-type:text/html;charset=utf-8");
	  if($_GET["action"]=="open"){
			$sql_file="system/sysregion/sysregion.sql";
			$table_name="sysregion";
  
			$db = Db::getInstance();
			$all_tables = $db->getTables();
			if(in_array($table_name,$all_tables)){
				alert("已经存在和{$table_name}同名的表无法导入数据表");
			}
			$sql_content=str_replace("\r\n", "\n",file_get_contents($sql_file));
			if($sql_content!==false){
				if(is_string($sql_content)) {
				   $querySql   =  explode(";\n", trim($sql_content)) ;
				}
				$ret = array();
				$num = 0;
				foreach($querySql as $query) {
				   $queries = explode("\n", trim($query));
				   foreach($queries as $query) {
					  $ret[$num] .= $query[0] == '#' || $query[0].$query[1] == '--' ? '' : $query;
				   }
				   $num++;
				}
				$dbname=C("DB_NAME");
				$db->execute('USE '.$dbName);
				foreach($ret as $query) {
				   if(!empty($query)) {
				      $result   = $db->execute($query);
				      if(false === $result) {
					    alert('sql语句执行失败');
				      }
				   }
				}
				alert('开启成功');
			 }else{
			  alert("读取{$sql_file}文件失败");  
		     }  
	  }else if($_GET["action"]=="close"){
		  $table_name="sysregion";
		  $del_sql="drop table $table_name";
		  $model=new Model;
		  $model->execute($del_sql);
		  alert('成功关闭');
	  }else{
		 $info_txt="system/sysregion/read.txt";
		 ob_start();
		 @readfile($info_txt);
		 $content=ob_get_contents();
		 ob_end_clean();
		 $this->assign("info",nl2br(iconv("gb2312","utf-8",$content)));//说明
		 
		 $this->display();  
	  }
  }
}
  //创建栏目
  //$column_name 栏目名称  $col_eng_name 表名 
 function create_sys_column($col_eng_name,$column_name=""){
	  if(empty($col_eng_name)) return false;
	  if(empty($column_name)) $column_name=$col_eng_name;
	  
	  $syscolumn=M("syscolumn");
	  $max_seq=$syscolumn->max("sequence");
	  $data["sequence"]=++$max_seq;
	  $data["col_name"]=$column_name;
	  $data["parid"]=0;
	  $data["col_eng_name"]=$col_eng_name;
	  $data["is_show"]=1;
	  
	  $parid=$syscolumn->add($data);

	  CreateModel($col_eng_name);
	  CreateAction($col_eng_name);
	  CreateTpl($col_eng_name);
	  
	  //添加栏目
	  $add_data["col_name"]="添加".$column_name;
	  $add_data["col_url"]="__APP__/Admin/".ucfirst($col_eng_name)."/add";
	  $add_data["sequence"]=2;
	  $add_data["parid"]=$parid;
	  //$add_data["col_eng_name"]=$col_eng_name;
	  $add_data["is_show"]=1;
	  $add_id=$syscolumn->add($add_data);
	  
	  //编辑栏目
	  $edit_data["col_name"]=$column_name."列表";
	  $edit_data["col_url"]="__APP__/Admin/".ucfirst($col_eng_name)."/index";
	  $edit_data["sequence"]=1;
	  $edit_data["parid"]=$parid;
	  //edit_data["col_eng_name"]=$col_eng_name;
	  $edit_data["is_show"]=1;
	  $edit_id=$syscolumn->add($edit_data);
	  //添加权限
	  $admin=M("admin");
	  $admin_user=$_SESSION["admin"];
	  $pression=$admin->where("admin='$admin_user'")->getField("pression");
	  $new_pression=implode(",",array_merge(explode(",",$pression),array("$parid","$add_id","$edit_id")));
	  $admin->where("admin='$admin_user'")->setField("pression",$new_pression);
	  return true;
}
function column_edit($eng_name,$k){
       //删除
	   $model_path=APP_NAME."/Lib/Model/".ucfirst($eng_name)."Model.class.php";
	   $tpl_dir=APP_NAME."/Tpl/default/Admin/".ucfirst($eng_name);
	   $action_path=APP_NAME."/Lib/Action/Admin/".ucfirst($eng_name)."Action.class.php";
	   Vendor("LJW.Inc_File");
	   $myfile=new Inc_File();
	   $myfile->deletefile($model_path);
	   $myfile->deletefile($action_path);
	   $myfile->deletedir($tpl_dir);
	   CreateModel($eng_name);
	   CreateAction($eng_name);
	   CreateTpl($eng_name);	
}
?>